import { Select2Page } from "../../../common/serve-request.js";
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import FeedingApi from '../../../common/api/cbs/feeding.api.js';
(function (window, document, $) {
    let _vm, savetype, getEntryInfo = [], allMaterialInfo = [], deliverDatas = {}
    $(function () {
        _vm = new Vue({
            el: "#saleordersentry-form",
            data() {
                return {
                    entries: [{
                        "seq": "",
                        "material": {
                            "id": "",
                            "name": "",
                            "numCode": "",
                            "baseMeasureUnit": "",
                            "subMeasureUnit": "",
                        },
                        "feedingCount": "",
                        "stockCount": "",
                    }],
                    uploadCount: 0
                }
            },
            mounted() {
                let url = location.href
                let params = {} // url参数
                for (let key of (new URL(url)).searchParams.entries()) {
                    key[1] ? params[key[0]] = key[1] : ''
                }
                if (params.isEdit == 'true') {
                    document.title = '饲喂记录分录 - 编辑'
                }
            },
            methods: {
                submit() {
                    if (!Utils.IsNotNull(_vm.entries[0]?.material.id)) {
                        return $.toptip(`请选择物料!`, 'warning');
                    }
                    if (!Utils.IsNotNull(_vm.entries[0].feedingCount)) {
                        return $.toptip(`请输入饲喂用量!`, 'warning');
                    }
                    var reg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/
                    // if (!_vm.entries[0].feedingCount.match(reg)) return $.toptip(`数量必须大于0并且只能保留两位小数`, 'warning')
                    if (!(reg.test(_vm.entries[0].feedingCount))) return $.toptip(`死亡均重必须大于0并且只能保留两位小数`, 'warning')
                    savetips({ ..._vm.entries[0] })
                }
            }
        });

        _initCommand();
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
    });

    // 初始化数据
    const _initCommand = async () => {
        let allMaterial = await FeedingApi.postMaterial()
        allMaterialInfo = allMaterial.items.filter(item => item.numCode.substring(0, 2) == '13')
        deliverDatas = JSON.parse(Utils.GetSessionStorage("deliverDatas")) || {}
        getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo")) || []
        let isEdit = JSON.parse(getUrlKey('isEdit'))
        let feedType = getUrlKey('feedType')
        let seq = getUrlKey('index')
        // 编辑时赋值
        if (isEdit) {
            let datas = getEntryInfo.find(item => item.seq == seq)
            _vm.entries[0].material.id = datas?.material.id
            _vm.entries[0].material.name = datas?.material.name
            _vm.entries[0].material.numCode = datas?.material.numCode
            _vm.entries[0].material.baseMeasureUnit = datas?.material.baseMeasureUnit
            _vm.entries[0].material.subMeasureUnit = datas?.material.subMeasureUnit
            _vm.entries[0].feedingCount = datas?.feedingCount
            // 带出库存数量
            let stockCount = await getmaterialStock(_vm.entries[0].material.id)
            _vm.entries[0].stockCount = stockCount || 0
        }
        // // 物料
        // Select2Page($(`#materialId`), `${Utils.CurDomain.MasterDataUrl}/yymaterials/q`, (params) => {
        //     return ({
        //         MGroupId: Utils.IsNotNull(feedType) ? feedType : DictionaryType.FEEDING_TYPE,
        //         SearchInfo: params.term,
        //         PageSize: 10,
        //         PageIndex: (params.page || 1) - 1
        //     })
        // }, "GET", {
        //     allowClear: true,//允许清空
        //     placeholder: '请选择物料...', //默认文字提示
        //     templateResult: function (res) {
        //         // _entriesMatrls = [{ id: "", text: "请选择物料..." }];
        //         if (Utils.IsNotNull(res.id)) {
        //             let sltHtml = {
        //                 id: res.id,
        //                 text: res.name,
        //                 name: res.name,
        //                 numCode: res.numCode,
        //                 baseMeasureUnit: res.baseMeasureUnit,
        //                 subMeasureUnit: res.subMeasureUnit,
        //                 textString: res.name + "," + res.numCode + "," + res.model + "," + res.baseMeasureUnit,
        //                 ...res
        //             }

        //             let sltSpanHtml = "";
        //             if (!res.id) {
        //                 return "";
        //             }
        //             let arr = sltHtml?.textString?.split(',');
        //             if (!arr) return;
        //             res.id == -1 ? "" : sltSpanHtml +=
        //                 `<div style='margin-bottom: 8px;color:#000'>${arr[0]}</div>
        //             <label style='font-size:0'>
        //             <span style="border: #3e8ef7 1px solid;background-color: #fff;padding : 2px 4px;color:#3e8ef7;font-size: 9px;border-radius: 10px 0 0 10px">${arr[1]}</span>
        //             <span style="border: #8A5082 1px solid;background-color: #8A5082;; padding : 2px 4px;color:#fff;font-size: 9px;">${arr[2]}</span>
        //             <span style="border: #758EB7 1px solid;background-color: #758EB7;; padding : 2px 4px;color:#fff;font-size: 9px;border-radius: 0 10px 10px 0;">${arr[3]}</span>
        //             </label>`;
        //             return $(`<span data-code = "${arr[1]}" data-name="${arr[0]}" data-model = "${arr[2]}" data-unit = "${arr[3]}">${sltSpanHtml}</span>`);
        //         }
        //     }
        // });
        // $(`#materialId`).setSelectValue(_vm.entries[0].material?.id, _vm.entries[0].material?.name);

        $(`#materialId`).empty().select2({
            placeholder: '请选择物料...',//默认文字提示
            language: "zh-CN",//汉化
            // allowClear: true,
            data: allMaterialInfo.map(item => {
                return {
                    id: item.id,
                    text: `${item.name}(${item.numCode})`,
                    name: item.name,
                    numCode: item.numCode,
                    model: item.model,
                    baseMeasureUnit: item.baseMeasureUnit,
                    subMeasureUnit: item.subMeasureUnit,
                }
            }),
            templateResult: function (res) {
                if (Utils.IsNotNull(res.id)) {
                    let sltHtml = {
                        id: res.id,
                        text: `${res.name}(${res.numCode})`,
                        name: res.name,
                        numCode: res.numCode,
                        baseMeasureUnit: res.baseMeasureUnit,
                        subMeasureUnit: res.subMeasureUnit,
                        textString: res.name + "," + res.numCode + "," + res.model + "," + res.baseMeasureUnit,
                        ...res
                    }

                    let sltSpanHtml = "";
                    if (!res.id) {
                        return "";
                    }
                    let arr = sltHtml?.textString?.split(',');
                    if (!arr) return;
                    res.id == -1 ? "" : sltSpanHtml +=
                        `<div style='margin-bottom: 8px;color:#000'>${arr[0]}</div>
                        <label style='font-size:0'>
                        <span style="border: #3e8ef7 1px solid;background-color: #fff;padding : 2px 4px;color:#3e8ef7;font-size: 9px;border-radius: 10px 0 0 10px">${arr[1]}</span>
                        <span style="border: #8A5082 1px solid;background-color: #8A5082;; padding : 2px 4px;color:#fff;font-size: 9px;">${arr[2]}</span>
                        <span style="border: #758EB7 1px solid;background-color: #758EB7;; padding : 2px 4px;color:#fff;font-size: 9px;border-radius: 0 10px 10px 0;">${arr[3]}</span>
                        </label>`;
                    return $(`<span data-code = "${arr[1]}" data-name="${arr[0]}" data-model = "${arr[2]}" data-unit = "${arr[3]}">${sltSpanHtml}</span>`);
                }
            }
        });
        $(`#materialId`).setSelectValue(_vm.entries[0].material?.id, _vm.entries[0].material?.name);
        let saleOrgsInfo = cutstr($('#select2-materialId-container').text(), 20)
        $('#select2-materialId-container').text(saleOrgsInfo)

        $('#materialId').on("select2:select", async function () {
            let selectMaterial = $('#materialId').select2('data')[0]
            _vm.entries[0].material.id = selectMaterial?.id
            _vm.entries[0].material.name = selectMaterial?.name
            _vm.entries[0].material.numCode = selectMaterial?.numCode
            _vm.entries[0].material.baseMeasureUnit = selectMaterial?.baseMeasureUnit
            _vm.entries[0].material.subMeasureUnit = selectMaterial?.subMeasureUnit
            let saleOrgsInfo = cutstr($('#select2-materialId-container').text(), 20)
            $('#select2-materialId-container').text(saleOrgsInfo)
            // 带出库存数量
            let stockCount = await getmaterialStock(_vm.entries[0].material.id)
            _vm.entries[0].stockCount = stockCount || 0
        })
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../feeding/addfeeding.html?v=${Utils.GetTime()}`;
        });
    }

    // 保存提示
    const savetips = (data) => {
        let saveEntry
        if (Utils.IsNotNull(getUrlKey("operaEntryId"))) {
            savetype = '修改'
            saveEntry = getUrlKey("operaEntryId")
        }
        else {
            savetype = '保存'
            saveEntry = getUrlKey('nextEntryId')
        }
        let tipsinfo = ''
        if (_vm.entries[0].feedingCount > _vm.entries[0].stockCount) {
            tipsinfo = '饲喂量大于库存数量，'
        }

        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
    				<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
    					<div>${tipsinfo}是否确认${savetype}该分录？</div>
    				</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        let seq = parseInt(getUrlKey('index'))
                        let isEdit = JSON.parse(getUrlKey('isEdit'))
                        // 新增
                        if (Utils.IsNotNull(getEntryInfo) && isEdit == false) {
                            getEntryInfo.push(data)
                        } else if (Utils.IsNotNull(getEntryInfo) && isEdit) {
                            // 编辑
                            getEntryInfo[seq] = data
                        } else {
                            getEntryInfo.push(data)
                        }
                        getEntryInfo.map((item, index) => {
                            item.seq = index
                        })
                        // 存入SessionStorage
                        JSON.stringify(Utils.SetSessionStorage("getEntryInfo", getEntryInfo))
                        location.href = `./addfeeding.html?v=${Utils.GetTime()}`;
                        $.closeModal();
                    }
                }
            ]
        });
    }

    // 获取地址栏的参数
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

    // 获取库存数量
    const getmaterialStock = async (materialId) => {
        if (Utils.IsNotNull(deliverDatas?.breedBatch?.id)) {
            let stockQuery = {
                "batchId": deliverDatas?.breedBatch?.id
            }
            // 获取库存地点
            let stockCode = await FeedingApi.getmaterialStock(stockQuery)
            if (Utils.IsNotNull(stockCode) && Utils.IsNotNull(deliverDatas?.farmOrg?.id)) {
                let stockNumQuery = {
                    "farmOrgId": deliverDatas?.farmOrg?.id,
                    "wareCode": stockCode
                }
                // 获取库存数量
                let stockNumAll = await FeedingApi.getStockNum(stockNumQuery)
                let stockNumInfo = stockNumAll.find(item => item.matnr == materialId)
                return stockNumInfo?.labst
            }
            else {
                return $.toptip(`暂未查询到库存地点信息！!`, 'warning');
            }
        }
    }

    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }
})(window, document, jQuery)